package com.csrcb.service;

import com.csrcb.constant.FileParamValue;
import com.csrcb.constant.ParamConstant;
import com.csrcb.dto.Text;
import com.csrcb.dto.WeChatAccessTokenTestEnvironment;
import com.csrcb.dto.WeChatSendMessage;
import com.csrcb.dto.WechatSendResponse;
import com.csrcb.tools.HttpSendContent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Classname WeChatService
 * @Description 使用微信服務
 * @Date 2020/12/16 13:43
 * @Created by gangye
 */
public class WeChatService {
    private static Logger logger = LoggerFactory.getLogger(WeChatService.class);

    /**
     * 通过appID和appsecret获取接口访问令牌access_token
     * @author qigangye
     * @date 2020年12月16日14:49:16
     */
    public String getAccessToken (){
        String accessToken = null;
        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(ParamConstant.GET_ACCESS_TOKEN_URL).append(ParamConstant.AND_SYMBOL)
                .append(ParamConstant.APP_ID).append(ParamConstant.EQUAL_SYMBOL)
                .append(FileParamValue.getAppid()).append(ParamConstant.AND_SYMBOL)
                .append(ParamConstant.APP_SECRET).append(ParamConstant.EQUAL_SYMBOL)
                .append(FileParamValue.getSecret());
        logger.info("获取accesstoken的get请求的路由:{}",requestUrl.toString());
        String response = HttpSendContent.doGet(requestUrl.toString(),ParamConstant.ACCTYPE_TYPE_JSON, null);
        logger.info("返回报文:{}",response);
        //将返回的json报文与定义的类的属性相映射
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            WeChatAccessTokenTestEnvironment wechatToken = objectMapper.readValue(response, WeChatAccessTokenTestEnvironment.class);
            accessToken = wechatToken.getAccessToken();
            logger.info("获得的口令:{}",accessToken);
        } catch (JsonProcessingException e) {
            logger.error("json格式转化异常:{}",response);
        }
        return accessToken;
    }

    /**
     * 调用微信发送信息，根据返回状态码值判断是否成功
     * @param message
     * @return
     */
    public boolean sendMessageWithToken (String message){
        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(ParamConstant.SEND_MESSAGE_URL).append(ParamConstant.QUESTION_SYMBOL)
                .append(ParamConstant.ACCESS_TOKEN).append(ParamConstant.EQUAL_SYMBOL)
                .append(this.getAccessToken());
        Text text = new Text();
        if (message == null || "".equals(message)){
            text.setContent("时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\n"+"地点:苏州");
        }else{
            text.setContent(message);
        }
        WeChatSendMessage weChatSendMessage = new WeChatSendMessage();
        weChatSendMessage.setTouser(FileParamValue.getTouser());
        weChatSendMessage.setMsgtype(ParamConstant.MSGTYPE_TEXT);
        weChatSendMessage.setText(text);
        String requestJson = null;
        try {
            requestJson = new ObjectMapper().writeValueAsString(weChatSendMessage);
            logger.info("发送消息请求路由：{}",requestUrl.toString());
            logger.info("发送消息请求json报文：{}",requestJson);
        } catch (JsonProcessingException e) {
            logger.error("将实体类映射为json字符串失败:{}",weChatSendMessage.toString());
        }
        String sendResponse = HttpSendContent.doPost(requestUrl.toString(),requestJson,ParamConstant.CONTENT_TYPE_JSON,ParamConstant.ACCTYPE_TYPE_JSON,null);
        logger.info("发送后返回的报文：{}",sendResponse);
        WechatSendResponse ws = new WechatSendResponse();
        try {
            ws = new ObjectMapper().readValue(sendResponse,WechatSendResponse.class);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
        }
        if (ws != null && "0".equals(ws.getErrcode())){
            return true;
        }else{
            return false;
        }
    }

}
